<?php

namespace App\Http\Controllers;

use App\Exceptions\ApiException;
use App\Http\Requests\StoreProductCategoryRequest;
use App\Http\Requests\UpdateProductCategoryRequest;
use App\Http\Resources\ServiceResource;
use App\Models\ProductCategory;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class ProductCategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, ProductCategory $model)
    {
        $pid = $request->pid;

        $model = $model->select(['id', ...$model->fillable]);

        if (is_null($pid)) {
            return $model->get();
        }
        return $model->where('pid', (int)$pid)->get();
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\StoreProductCategoryRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreProductCategoryRequest $request)
    {
        return $this->successful(ProductCategory::create($request->all()));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\ProductCategory  $productCategory
     * @return \Illuminate\Http\Response
     */
    public function show(ProductCategory $productCategory)
    {
        return $this->successful($productCategory);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Http\Requests\UpdateProductCategoryRequest  $request
     * @param  \App\Models\ProductCategory  $productCategory
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateProductCategoryRequest $request, ProductCategory $productCategory)
    {
        return $this->successful($productCategory->update($request->all()));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\ProductCategory  $productCategory
     * @return \Illuminate\Http\Response
     */
    public function destroy(ProductCategory $productCategory)
    {
        if ($productCategory->children()->count() > 0) {
            throw new ApiException('该分类下有子分类，不能删除', 501);
        }
        if ($productCategory->products->count() > 0) {
            throw new ApiException('该分类下有商品，不能删除', 501);
        }
        // $productCategory->delete();
        return $this->successful();
    }

    /**
     * Delete many resources
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function deleteMany(Request $request)
    {
        $ids = $request->ids;
        if (empty($ids)) {
            return $this->fail(400, 'ids is required');
        }
        ProductCategory::whereIn('id', $ids)->delete();
        return $this->successful($ids);
    }
}
